package com.example.mcp.config;

import org.springframework.ai.openai.OpenAiChatModel;
import org.springframework.ai.openai.OpenAiChatOptions;
import org.springframework.ai.openai.api.OpenAiApi;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.web.client.RestClient;
import org.springframework.web.reactive.function.client.WebClient;

/**
 * AI聊天配置类
 * 配置自定义的OpenAI客户端以支持中转服务
 * 
 * @author Generated
 * @version 1.0.0
 */
@Configuration
public class McpConfig {
    
    @Value("${spring.ai.openai.base-url}")
    private String baseUrl;
    
    @Value("${spring.ai.openai.api-key}")
    private String apiKey;
    
    /**
     * 配置自定义的OpenAI API客户端
     * 添加响应拦截器来修复兼容性问题
     */
    @Bean
    @Primary
    public OpenAiApi customOpenAiApi(OpenAiResponseInterceptor responseInterceptor) {
        RestClient.Builder restClientBuilder = RestClient.builder()
                .baseUrl(baseUrl)
                .defaultHeader("Authorization", "Bearer " + apiKey)
                .requestInterceptors(interceptors -> {
                    interceptors.add(responseInterceptor);
                });
        
        WebClient.Builder webClientBuilder = WebClient.builder()
                .baseUrl(baseUrl)
                .defaultHeader("Authorization", "Bearer " + apiKey);
        
        // 使用正确的构造函数签名
        return new OpenAiApi(baseUrl, apiKey, restClientBuilder, webClientBuilder);
    }
    
    /**
     * 配置自定义的OpenAI聊天模型
     */
    @Bean
    @Primary
    public OpenAiChatModel customOpenAiChatModel(OpenAiApi openAiApi) {
        // 创建聊天选项，使用配置文件中指定的模型
        var chatOptions = org.springframework.ai.openai.OpenAiChatOptions.builder()
                .withModel("gemini-2.5-pro")  // 恢复为与API密钥匹配的模型
                .withTemperature(0.8)
                .withMaxTokens(20000)  // 大幅增加token限制以支持复杂的工具调用和推理链
                .withTopP(0.9)
                .build();
        
        return new OpenAiChatModel(openAiApi, chatOptions);
    }
}
